package com.lr.generatorplus.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import javax.net.ssl.*;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


public class HttpUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

	private static CloseableHttpClient httpClient;
	private static final Integer REQ_TIMEOUT = 60000;     //请求超时时间ms
	private static final Integer CONN_TIMEOUT = 60000;     //连接超时时间ms
	private static final Integer SOCK_TIMEOUT = 60000;    //读取超时时间ms
	private static  String ip="116.62.194.248";
	private static  int port=3128;

	static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(50000);
        cm.setDefaultMaxPerRoute(500);
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectionRequestTimeout(REQ_TIMEOUT)
				.setConnectTimeout(CONN_TIMEOUT).setSocketTimeout(SOCK_TIMEOUT)
				.build();
		HttpRequestRetryHandler requestRetryHandler=new HttpRequestRetryHandler() {
			public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
				if (executionCount > 3) //超过重试次数，就放弃
					return false;
				if (exception instanceof NoHttpResponseException) {//没有响应，重试
					return true;
				}else if (exception instanceof ConnectTimeoutException) {//连接超时，重试
					return true;
				} else if (exception instanceof SocketTimeoutException) {//连接或读取超时，重试
					return true;
				}else if (exception instanceof SSLHandshakeException) {//本地证书异常
					return false;
				} else if (exception instanceof InterruptedIOException) {//被中断
					return false;
				} else if (exception instanceof UnknownHostException) {//找不到服务器
					return false;
				}  else if (exception instanceof SSLException) {//SSL异常
					return false;
				} else {
					LOGGER.error("未记录的请求异常：" + exception.getClass());
				}
				HttpClientContext clientContext = HttpClientContext.adapt(context);
				HttpRequest request = clientContext.getRequest();
				// 如果请求是幂等的，则重试
				if (!(request instanceof HttpEntityEnclosingRequest)) return true;
				return false;
			}
		};

		httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).setRetryHandler(requestRetryHandler).build();
		LOGGER.info("---------------------totalStats:{}", cm.getTotalStats());

	}

	private static CloseableHttpClient getHttpsClient(String qlb, String port) {
		//这里设置客户端不检测服务器ssl证书
		try {
			X509TrustManager x509mgr = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] xcs, String string) {
				}
				public void checkServerTrusted(X509Certificate[] xcs, String string) {
				}
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[] { x509mgr }, null);
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			HttpHost proxy = new HttpHost(qlb, Integer.parseInt(port), "https");
			RequestConfig defaultRequestConfig = RequestConfig.custom()
					.setProxy(proxy)
					.build();
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();
			return httpclient;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
    public static String get(String url) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            response = httpClient.execute(httpGet);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

	public static String getProxy(String url,String ipProxy) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			String data[]=ipProxy.split(":");
			HttpGet httpGet = new HttpGet(url);
			HttpHost proxy = new HttpHost(data[0], Integer.parseInt(data[1]), "http");
			RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);
			response = httpClient.execute(httpGet);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String getHttpsProxy(String url,String ipProxy) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpGet httpGet = new HttpGet(url);
			String data[]=ipProxy.split(":");
			httpClient=getHttpsClient(data[0],data[1]);
			response = httpClient.execute(httpGet);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String getHeader(String url,Map<String,String> header) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpGet.addHeader(key, val);
			}
			response = httpClient.execute(httpGet);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}


	public static String getHeaderFile(String url,Map<String,String> header,String path) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpGet.addHeader(key, val);
			}
			response = httpClient.execute(httpGet);
			downloadFile(response.getEntity(),path);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}


	public static String getXml(String url) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);
			httpGet.setConfig(requestConfig);
			httpGet.addHeader("Content-type", "application/json; charset=utf-8");
			httpGet.setHeader("Accept", "application/json");
			response = httpClient.execute(httpGet);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	public static CloseableHttpResponse getInputStream(String url) throws Exception{
		CloseableHttpResponse response = null;
		InputStream in = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);
			httpGet.setConfig(requestConfig);
			httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.19 Safari/537.36");
			response = httpClient.execute(httpGet);
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	public static String getZip(String url) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
			httpGet.setConfig(requestConfig);
			httpGet.setConfig(requestConfig);
			httpGet.addHeader("Content-type", "application/json; charset=utf-8");
			httpGet.setHeader("Accept", "application/json");
			httpGet.setHeader("Content-Encoding", "gzip");
			httpGet.setHeader("Transfer-Encoding", "chunked");
			response = httpClient.execute(httpGet);
			InputStream is=response.getEntity().getContent();
			is= new GZIPInputStream(is);
			in = new BufferedReader(new InputStreamReader(is));
			//in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}


    public static String post(String url, String jsonString)throws Exception {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
		HttpPost httpPost =null;
        try {
             httpPost = new HttpPost(url);
			httpPost.setHeader("Cookie","PHPSESSID=8f6e3c1e335e4c1984c0c80258a62379");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
			HttpEntity entity =response.getEntity();
			if(entity!=null) {
				result = EntityUtils.toString(entity,Charset.forName("UTF-8"));
			}
        } catch (Exception e) {
        	httpPost.abort();
        	throw e;
        } finally {
            try {
            	if(httpPost!=null){
					httpPost.releaseConnection();
				}
            	if(in!=null){
					in.close();
				}
                if (null != response) {
                    response.close();
					EntityUtils.consume(response.getEntity());
                }
            } catch (Exception e) {
				throw e;
            }
        }
        return result;
    }

	public static String postHeader(String url, String jsonString,Map<String,String> header)throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		HttpPost httpPost =null;
		try {
			httpPost = new HttpPost(url);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpPost.addHeader(key, val);
			}
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
				httpPost.addHeader("Accept", "application/json, text/plain, */*");
			httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			HttpEntity entity =response.getEntity();
			if(entity!=null) {
				result = EntityUtils.toString(entity,Charset.forName("UTF-8"));
			}
		} catch (Exception e) {
			httpPost.abort();
			throw e;
		} finally {
			try {
				if(httpPost!=null){
					httpPost.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}


	public static String putHeader(String url, String jsonString,Map<String,String> header)throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		HttpPut put =null;
		try {
			put = new HttpPut(url);
			for(String key:header.keySet()){
				String val=header.get(key);
				put.addHeader(key, val);
			}
			put.addHeader("Content-type", "application/json; charset=utf-8");
			put.addHeader("Accept", "application/json, text/plain, */*");
			put.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
			response = httpClient.execute(put);
			HttpEntity entity =response.getEntity();
			if(entity!=null) {
				result = EntityUtils.toString(entity,Charset.forName("UTF-8"));
			}
		} catch (Exception e) {
			put.abort();
			throw e;
		} finally {
			try {
				if(put!=null){
					put.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}

	public static String postFormGetFile(String url, Map<String, String> reqMap,Map<String,String> header,String path)throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		HttpPost httpPost =null;

		try {
			httpPost = new HttpPost(url);
			httpPost = new HttpPost(url);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpPost.addHeader(key, val);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(execute(reqMap),Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			HttpEntity entity =response.getEntity();
			downloadFile(entity,path);
		} catch (Exception e) {
			httpPost.abort();
			throw e;
		} finally {
			try {
				if(httpPost!=null){
					httpPost.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}

	public static void downloadFile(HttpEntity entity, String path) throws IOException {
		if(entity!=null) {
			InputStream instreams = entity.getContent();
			File saveFile = new File(path);
			// 判断这个文件（saveFile）是否存在
			if (!saveFile.getParentFile().exists()) {
				// 如果不存在就创建这个文件夹
				saveFile.getParentFile().mkdirs();
			}
			saveToImgByInputStream(instreams,path);
		}
	}
	public static String postHeaderFile(String url,String path, Map<String,String> header)throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		HttpPost httpPost =null;

		try {
			httpPost = new HttpPost(url);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpPost.addHeader(key, val);
			}
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			File file = new File(path);
			System.out.println(file.getName());
			multipartEntityBuilder.addBinaryBody("file",file);
			HttpEntity httpEntity = multipartEntityBuilder.build();
			httpPost.setEntity(httpEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity =response.getEntity();
			if(entity!=null) {
				result = EntityUtils.toString(entity,Charset.forName("UTF-8"));
			}
		} catch (Exception e) {
			httpPost.abort();
			throw e;
		} finally {
			try {
				if(httpPost!=null){
					httpPost.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}

	public static String postFile(String url,String path,String token)throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		HttpPost httpPost =null;

		try {
			httpPost = new HttpPost(url);
			httpPost.setHeader("Cookie","PHPSESSID="+token);
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			File file = new File(path);
			System.out.println(file.getName());
			multipartEntityBuilder.addBinaryBody("file",file);
			StringBody value = new StringBody("0", ContentType.create("multipart/form-data", Consts.UTF_8));
			multipartEntityBuilder.addPart("id", value);
			multipartEntityBuilder.addPart("type",  new StringBody("1", ContentType.create("multipart/form-data", Consts.UTF_8)));
			HttpEntity httpEntity = multipartEntityBuilder.build();
			httpPost.setEntity(httpEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity =response.getEntity();
			if(entity!=null) {
				result = EntityUtils.toString(entity,Charset.forName("UTF-8"));
			}
		} catch (Exception e) {
			httpPost.abort();
			throw e;
		} finally {
			try {
				if(httpPost!=null){
					httpPost.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}

	/*
	 * @param instreams 二进制流
	 *
	 * @param imgPath 图片的保存路径
	 *
	 * @param imgName 图片的名称
	 *
	 * @return 1：保存正常 0：保存失败
	 */
	private static int saveToImgByInputStream(InputStream instreams, String imgPath) {

		int stateInt = 1;
		if (instreams != null) {
			try {
				File file = new File(imgPath);// 可以是任何图片格式.jpg,.png等
				FileOutputStream fos = new FileOutputStream(file);

				byte[] b = new byte[1024];
				int nRead = 0;
				while ((nRead = instreams.read(b)) != -1) {
					fos.write(b, 0, nRead);
				}
				fos.flush();
				fos.close();
			} catch (Exception e) {
				stateInt = 0;
				e.printStackTrace();
			} finally {
				try {
					instreams.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return stateInt;
	}

	public static String delete(String url)throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		HttpDelete httpDelete =null;
		try {
			httpDelete = new HttpDelete(url);
			httpDelete.addHeader("Content-type", "application/json; charset=utf-8");
			response = httpClient.execute(httpDelete);
			HttpEntity entity =response.getEntity();
			if(entity!=null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			httpDelete.abort();
			throw e;
		} finally {
			try {
				if(httpDelete!=null){
					httpDelete.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}
	public static String postZip(String url, String jsonString) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			ByteArrayOutputStream originalContent = new ByteArrayOutputStream();
			originalContent
					.write(jsonString.getBytes(Charset.forName("UTF-8")));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
			originalContent.writeTo(gzipOut);
			gzipOut.finish();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
			httpPost.setConfig(requestConfig);
			httpPost.setConfig(requestConfig);
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-Encoding", "gzip");
			httpPost.setEntity(new ByteArrayEntity(baos.toByteArray()));
			response = httpClient.execute(httpPost);
			in = new BufferedReader(new InputStreamReader(new GZIPInputStream(response.getEntity().getContent())));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String Send(String method, String url, String data) {
		HttpURLConnection conn = null;
		InputStream in = null;
		InputStreamReader isr = null;
		OutputStream out = null;
		StringBuffer result = null;
		try {

			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setRequestProperty("Accept-Encoding", "gzip");
			//conn.setRequestProperty("Content-Type", "");
			conn.setRequestProperty("Connection", "keep-alive");

			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(60000);
			conn.setReadTimeout(60000);

			if (method.equals("POST")) {
				byte[] sendbyte = data.getBytes("UTF-8");
				out = conn.getOutputStream();
				out.write(sendbyte);
			}

			int status = conn.getResponseCode();
			if (status == 200) {
				String enc = conn.getContentEncoding();
				result = new StringBuffer();
				in = conn.getInputStream();
				enc = conn.getContentEncoding();

				if (enc != null && enc.equals("gzip")) {
					GZIPInputStream gzin = new GZIPInputStream(in);
					isr = new InputStreamReader(gzin, "UTF-8");

				} else {
					isr = new InputStreamReader(in, "UTF-8");
				}

				char[] c = new char[1024];
				int a = isr.read(c);
				while (a != -1) {
					result.append(new String(c, 0, a));
					a = isr.read(c);
				}
			} else {
				System.out.println("http code = " + status);

			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
			try {
				if (in != null) {
					in.close();
				}
				if (isr != null) {
					isr.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result == null ? null : result + "";
	}

	public static String toFormatedXML(Document object) throws Exception {
		Document doc = (Document) object;
		TransformerFactory transFactory = TransformerFactory.newInstance();
		Transformer transFormer = transFactory.newTransformer();
		transFormer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
		DOMSource domSource = new DOMSource(doc);

		StringWriter sw = new StringWriter();
		StreamResult xmlResult = new StreamResult(sw);

		transFormer.transform(domSource, xmlResult);

		return sw.toString();

	}



	public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));

		StringBuilder sb = new StringBuilder();

		String line = null;

		try {

			while ((line = reader.readLine()) != null) {

				sb.append(line);

			}

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				is.close();

			} catch (IOException e) {

				e.printStackTrace();

			}

		}

		return sb.toString();

	}

	 /**
	   * 从远程URL下载文件到本地保存
	   *
	 * @param remoteUrl
	 * @param savePath
	 * @throws IOException
	 */
	public static void downloadNet(String remoteUrl,String savePath) throws MalformedURLException,FileNotFoundException,IOException {
	        // 下载网络文件
	        int bytesum = 0;//记录文件大小
	        int byteread = 0;

	        InputStream inStream=null;
	        FileOutputStream fs=null;
	        try {
	        	URLConnection conn = new URL(remoteUrl).openConnection();
	            inStream = conn.getInputStream();
	            fs = new FileOutputStream(savePath);

	            byte[] buffer = new byte[1204];
	            while ((byteread = inStream.read(buffer)) != -1) {
	                bytesum += byteread;
	                fs.write(buffer, 0, byteread);
	            }
	            //LOGGER.error("文件下载成功！下载地址：{}，存放文件名称：{}，文件大小：{} k",remoteUrl,savePath,bytesum/1024);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				LOGGER.error("远程URL路径格式错误！{}",remoteUrl);
				throw new MalformedURLException();
	        } catch (FileNotFoundException e) {
	            LOGGER.error("远程文件不存在！{}",remoteUrl,e);
	            throw new FileNotFoundException();
	        } catch (IOException e) {
	        	LOGGER.error(savePath+"文件{}写入失败！",e);
	        	//throw new IOException();
	        }finally{
	        	if(inStream!=null){
	        		try {
						inStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						LOGGER.error("关闭下载文件流失败",e);
					}
	        	}
	        	if(fs!=null){
		        	try {
						fs.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						LOGGER.error("关闭写入文件流失败",e);
					}
	        	}
	        }
	    }
	
	public static String URLEncoder(JSONObject json){

        StringBuffer req = new StringBuffer();
        try {
            String encode = URLEncoder.encode(json.toJSONString(), "UTF-8");
            req.append("?reqData=" +encode);
        } catch (UnsupportedEncodingException e){
            req.append("?reqData=");
        }

        return req.toString();
}

	public static List<NameValuePair> execute(Map<String, String> reqMap) {
		List<NameValuePair> data=new ArrayList<>(reqMap.keySet().size());
		Set<String> keySet = reqMap.keySet();
		for(String key:keySet){
			data.add(new BasicNameValuePair(key,reqMap.get(key)));
		}
		return data;
	}

	public static String postForm(String url, Map<String, String> reqMap) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			int timeout=300000;
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new UrlEncodedFormEntity(execute(reqMap),Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}


	public static String postFormHeader(String url, List<NameValuePair> data, Map<String,String> header) {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			int timeout=300000;
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
			httpPost.setConfig(requestConfig);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpPost.addHeader(key, val);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(data,Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String postFormHead(String url,Map<String, String> reqMap,Map<String,String> header) throws Exception {
		CloseableHttpResponse response = null;
		BufferedReader in = null;
		String result = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			for(String key:header.keySet()){
				String val=header.get(key);
				httpPost.addHeader(key, val);
			}
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new UrlEncodedFormEntity(execute(reqMap),Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	public static String postXml(String url, String xml)throws Exception {
		CloseableHttpResponse response = null;
		HttpPost httpPost =null;
		BufferedReader in = null;
		String result = "";
		try {
			 httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
			httpPost.setConfig(requestConfig);
			httpPost.setConfig(requestConfig);
			httpPost.addHeader("Content-Type","text/xml");
			httpPost.setEntity(new StringEntity(xml, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} catch (Exception e) {
			httpPost.abort();
			throw e;
		} finally {
			try {
				if(httpPost!=null){
					httpPost.releaseConnection();
				}
				if(in!=null){
					in.close();
				}
				if (null != response) {
					response.close();
					EntityUtils.consume(response.getEntity());
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return result;
	}
}
